<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能客服</title>
    <!-- 引入axios库 -->
    <script src="/home/js/axios.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        /* 系统通用样式 - 优化版本 */
        body {
            font-family: "Hiragino Sans GB", "Microsoft YaHei", SimHei, SimSun, sans-serif;
            margin: 0;
            padding: 0;
            background-color: transparent;
            font-size: 14px;
            color: #333;
        }

        /* 重置样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        /* 聊天容器 - 符合系统风格 */
        .chat-container {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        /* 聊天头部 - 豪华渐变版 */
        .chat-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 18px 20px;
            cursor: pointer;
            position: relative;
            border-radius: 8px 8px 0 0;
            box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
            overflow: hidden;
        }

        .chat-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
            transition: left 0.5s ease;
        }

        .chat-header:hover::before {
            left: 100%;
        }

        .chat-header h1 {
            font-size: 20px;
            font-weight: 700;
            margin: 0;
            text-align: center;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            position: relative;
            z-index: 1;
        }

        .chat-header h1 .emoji {
            display: inline-block;
            animation: bounce 2s infinite;
        }

        @keyframes bounce {
            0%, 20%, 50%, 80%, 100% {
                transform: translateY(0);
            }
            40% {
                transform: translateY(-3px);
            }
            60% {
                transform: translateY(-2px);
            }
        }

        /* 聊天内容区域 - 优化样式 */
        .chat-messages {
            flex: 1;
            padding: 15px;
            overflow-y: auto;
            background: #f5f7fa;
            scroll-behavior: smooth;
            font-size: 14px;
        }

        .chat-messages::-webkit-scrollbar {
            width: 5px;
        }

        .chat-messages::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        .chat-messages::-webkit-scrollbar-thumb {
            background: #d0d0d0;
            border-radius: 5px;
        }

        /* 消息样式 - 现代化设计升级版 */
        .message {
            margin-bottom: 18px;
            display: flex;
            align-items: flex-start;
            gap: 12px;
            animation: fadeInUp 0.3s ease-out;
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .message.user {
            flex-direction: row-reverse;
        }

        .message.bot {
            flex-direction: row;
        }

        .message.system {
            display: block;
            text-align: center;
            max-width: 100%;
            margin: 15px auto;
        }

        .message-content {
            max-width: 75%;
            padding: 14px 18px;
            border-radius: 18px;
            word-wrap: break-word;
            line-height: 1.6;
            position: relative;
            font-size: 14px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transition: all 0.2s ease;
        }

        .message-content:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .user .message-content {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-bottom-right-radius: 4px;
            position: relative;
        }

        .user .message-content::before {
            content: '';
            position: absolute;
            right: -8px;
            top: 12px;
            width: 0;
            height: 0;
            border-left: 8px solid #764ba2;
            border-top: 8px solid transparent;
            border-bottom: 8px solid transparent;
        }

        .bot .message-content {
            background: white;
            color: #333;
            border: 1px solid #e8e8e8;
            border-bottom-left-radius: 4px;
            position: relative;
        }

        .bot .message-content::before {
            content: '';
            position: absolute;
            left: -8px;
            top: 12px;
            width: 0;
            height: 0;
            border-right: 8px solid white;
            border-top: 8px solid transparent;
            border-bottom: 8px solid transparent;
        }

        .system .message-content {
            background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
            color: #8b4513;
            font-style: italic;
            max-width: 80%;
            margin: 0 auto;
            border-radius: 25px;
            box-shadow: 0 2px 8px rgba(251, 182, 159, 0.3);
        }

        .message-time {
            font-size: 11px;
            color: #bbb;
            margin-top: 6px;
            text-align: center;
            display: block;
            font-weight: 300;
        }

        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            flex-shrink: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            background: #f0f0f0;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
            transition: all 0.2s ease;
            border: 2px solid transparent;
        }

        .message-avatar:hover {
            transform: scale(1.1);
            border-color: rgba(52, 128, 226, 0.3);
        }

        .user .message-avatar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .bot .message-avatar {
            background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
            color: #3480e2;
            font-weight: bold;
        }

        /* 格式化内容样式优化 */
        .message-content h1,
        .message-content h2,
        .message-content h3,
        .message-content h4,
        .message-content h5,
        .message-content h6 {
            margin: 12px 0 8px 0;
            font-weight: 600;
            color: #2d3748;
            line-height: 1.3;
        }

        .message-content h1 { 
            font-size: 18px; 
            border-bottom: 2px solid #e2e8f0; 
            padding-bottom: 4px; 
            color: #667eea;
        }
        .message-content h2 { 
            font-size: 16px; 
            color: #764ba2;
        }
        .message-content h3 { 
            font-size: 15px; 
            color: #4c51bf;
        }
        .message-content h4 { 
            font-size: 14px; 
            color: #553c9a;
        }
        .message-content h5 { 
            font-size: 13px; 
            color: #718096; 
        }
        .message-content h6 { 
            font-size: 12px; 
            color: #a0aec0; 
        }

        .message-content p {
            margin: 8px 0;
            line-height: 1.6;
        }

        .message-content strong {
            font-weight: 600;
            color: #2d3748;
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1));
            padding: 1px 3px;
            border-radius: 3px;
        }

        .message-content em {
            font-style: italic;
            color: #4a5568;
            background: rgba(76, 81, 191, 0.1);
            padding: 1px 2px;
            border-radius: 3px;
        }

        .message-content ul,
        .message-content ol {
            margin: 8px 0;
            padding-left: 20px;
        }

        .message-content li {
            margin: 4px 0;
            line-height: 1.5;
        }

        .message-content ul li::marker {
            color: #667eea;
            font-size: 14px;
        }

        .message-content ol li::marker {
            color: #764ba2;
            font-weight: 600;
        }

        .message-content blockquote {
            margin: 8px 0;
            padding: 8px 16px;
            border-left: 4px solid #667eea;
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));
            border-radius: 0 8px 8px 0;
            font-style: italic;
        }

        .message-content code {
            background: rgba(0, 0, 0, 0.05);
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 13px;
            font-family: 'Courier New', monospace;
            color: #e53e3e;
            border: 1px solid rgba(229, 62, 62, 0.2);
        }

        .message-content pre {
            background: rgba(0, 0, 0, 0.05);
            padding: 12px;
            border-radius: 8px;
            overflow-x: auto;
            margin: 8px 0;
            border: 1px solid rgba(0, 0, 0, 0.1);
        }

        .message-content pre code {
            background: none;
            padding: 0;
            color: #2d3748;
            border: none;
        }

        .message-content a {
            color: #667eea;
            text-decoration: none;
            border-bottom: 1px solid transparent;
            transition: border-color 0.2s ease;
            padding: 1px 2px;
            border-radius: 2px;
        }

        .message-content a:hover {
            background: rgba(102, 126, 234, 0.1);
            border-bottom-color: #667eea;
        }

        /* 特殊处理：列表容器样式 */
        .message-content ul {
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.03), rgba(118, 75, 162, 0.03));
            padding: 8px 16px;
            border-radius: 8px;
            border-left: 3px solid #667eea;
        }

        .message-content ul li {
            position: relative;
            padding-left: 8px;
        }

        .message-content ul li::before {
            content: '•';
            color: #667eea;
            font-weight: bold;
            position: absolute;
            left: -8px;
        }

        /* 输入区域 - 豪华升级版样式 */
        .chat-input-area {
            padding: 18px;
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
            border-top: 1px solid #e8e8e8;
            display: flex;
            gap: 12px;
            align-items: flex-end;
            position: relative;
        }

        .chat-input-area::before {
            content: '';
            position: absolute;
            top: 0;
            left: 20px;
            right: 20px;
            height: 1px;
            background: linear-gradient(90deg, transparent 0%, #e8e8e8 50%, transparent 100%);
        }

        #messageInput {
            flex: 1;
            padding: 12px 20px;
            border: 2px solid #e0e0e0;
            border-radius: 25px;
            font-size: 14px;
            outline: none;
            font-family: "Hiragino Sans GB", "Microsoft YaHei", SimHei, SimSun, sans-serif;
            resize: none;
            max-height: 100px;
            min-height: 45px;
            transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
        }

        #messageInput:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
            background: rgba(255, 255, 255, 1);
            transform: translateY(-1px);
        }

        /* 发送按钮 - 豪华渐变版 */
        .chat-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 50%;
            width: 45px;
            height: 45px;
            font-size: 18px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            flex-shrink: 0;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
            position: relative;
            overflow: hidden;
        }

        .chat-btn::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            transform: translate(-50%, -50%);
            transition: all 0.3s ease;
        }

        .chat-btn:hover:not(:disabled)::before {
            width: 100%;
            height: 100%;
        }

        .chat-btn:hover:not(:disabled) {
            background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
            transform: scale(1.1) translateY(-2px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
        }

        .chat-btn:active {
            transform: scale(0.95);
        }

        .chat-btn:disabled {
            background: linear-gradient(135deg, #cbd5e0 0%, #a0aec0 100%);
            cursor: not-allowed;
            box-shadow: 0 2px 8px rgba(160, 174, 192, 0.3);
        }

        /* 清空按钮 - 美化升级版 */
        .clear-btn {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
            color: white;
            border: none;
            border-radius: 50%;
            width: 32px;
            height: 32px;
            font-size: 14px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            box-shadow: 0 3px 10px rgba(255, 107, 107, 0.3);
        }

        .clear-btn:hover {
            background: linear-gradient(135deg, #ff5252 0%, #e53e3e 100%);
            transform: scale(1.1) rotate(90deg);
            box-shadow: 0 5px 15px rgba(255, 107, 107, 0.4);
        }

        /* 最小化按钮 - 美化升级版 */
        .minimize-btn {
            background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
            color: white;
            border: none;
            border-radius: 50%;
            width: 32px;
            height: 32px;
            font-size: 12px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            box-shadow: 0 3px 10px rgba(78, 205, 196, 0.3);
        }

        .minimize-btn:hover {
            background: linear-gradient(135deg, #26d0ce 0%, #1a9cb0 100%);
            transform: scale(1.1);
            box-shadow: 0 5px 15px rgba(78, 205, 196, 0.4);
        }

        /* 状态指示器 - 美化升级版 */
        .chat-status {
            margin-top: 12px;
            font-size: 12px;
            color: #666;
            text-align: center;
            padding: 8px 0;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 15px;
            margin: 8px 15px 15px 15px;
            box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .chat-status span {
            color: #667eea;
            font-weight: 500;
        }

        /* 状态区域 */
        .chat-status {
            margin-top: 10px;
            font-size: 12px;
            color: #666;
            text-align: center;
        }

        /* 操作按钮 - 简化版 */
        .header-btn {
            position: absolute;
            top: 10px;
            background: rgba(255, 255, 255, 0.2);
            border: none;
            border-radius: 50%;
            width: 28px;
            height: 28px;
            color: white;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            transition: background 0.2s ease;
        }

        .header-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }

        .clear-btn {
            right: 45px;
        }

        .minimize-btn {
            right: 10px;
        }

        /* 加载状态动画 - 豪华升级版 */
        .typing-indicator {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 15px 20px;
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            border: 1px solid #e8e8e8;
            border-radius: 20px;
            border-bottom-left-radius: 6px;
            margin-bottom: 18px;
            max-width: 75%;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            position: relative;
            overflow: hidden;
            animation: fadeInUp 0.3s ease-out;
        }

        .typing-indicator::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(102, 126, 234, 0.05), transparent);
            animation: shine 2s infinite;
        }

        @keyframes shine {
            0% { left: -100%; }
            100% { left: 100%; }
        }
        
        .typing-indicator .dots {
            display: flex;
            gap: 6px;
        }
        
        .typing-indicator .dot {
            width: 10px;
            height: 10px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 50%;
            animation: typing 1.4s infinite ease-in-out both;
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
        }
        
        .typing-indicator .dot:nth-child(1) {
            animation-delay: -0.32s;
        }
        
        .typing-indicator .dot:nth-child(2) {
            animation-delay: -0.16s;
        }
        
        .typing-indicator .dot:nth-child(3) {
            animation-delay: 0s;
        }
        
        @keyframes typing {
            0%, 80%, 100% {
                transform: scale(0.8);
                opacity: 0.5;
            }
            40% {
                transform: scale(1.2);
                opacity: 1;
            }
        }

        .typing-indicator .typing-text {
            font-size: 14px;
            color: #666;
            font-weight: 500;
            margin-right: 8px;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .chat-container {
                border-radius: 0;
                box-shadow: none;
            }

            .message-content {
                max-width: 80%;
                padding: 10px 12px;
            }
            
            .typing-indicator {
                max-width: 80%;
            }
        }
    </style>
</head>
<body>
<div class="chat-container" id="chatContainer">
    <div class="chat-header" id="chatHeader">
        <button class="header-btn clear-btn" id="clearButton" title="清空聊天记录">
            ✕
        </button>
        <h1><span class="emoji">🤖</span> 中国梦想游智能客服</h1>
        <button class="header-btn minimize-btn" id="minimizeButton" title="最小化">
            —
        </button>
    </div>

    <div class="chat-messages" id="messagesContainer">
        <div class="message system">
            <div class="message-content">
                您好！我是中国梦想游智能客服，很高兴为您服务。请输入您的问题，我会尽力为您解答。
            </div>
            <span class="message-time">刚刚</span>
        </div>
    </div>

    <div class="chat-input-area">
        <textarea id="messageInput" placeholder="请输入您想咨询的问题..." rows="1"></textarea>
        <button class="chat-btn" id="sendButton" title="发送消息">
            →
        </button>
    </div>

    <div class="chat-status" id="status">
        <span id="connectionStatus">连接状态: 就绪</span>
    </div>
</div>

<script src="/home/js/config.js"></script>
<script>
    // DOM元素获取 - 优化版
    const messageInput = document.getElementById('messageInput');
    const sendButton = document.getElementById('sendButton');
    const clearButton = document.getElementById('clearButton');
    const chatContainer = document.getElementById('chatContainer');
    const messagesContainer = document.getElementById('messagesContainer');
    const connectionStatus = document.getElementById('connectionStatus');
    const chatHeader = document.getElementById('chatHeader');

    // 基础URL - 用于API调用
    const API_BASE_URL = 'https://api.coze.cn';

    // 缓存常用DOM元素
    let isMinimized = false;
    const minimizeButton = document.getElementById('minimizeButton');

    // 初始化事件监听 - 优化版本
    function initEventListeners() {
        // 输入框自动调整高度
        messageInput.addEventListener('input', adjustTextareaHeight);

        // 发送按钮点击事件
        sendButton.addEventListener('click', sendMessage);

        // 清空按钮点击事件
        clearButton.addEventListener('click', clearChatHistory);

        // 最小化按钮点击事件
        minimizeButton.addEventListener('click', function(e) {
            e.stopPropagation(); // 阻止冒泡到头部
            toggleMinimize();
        });

        // 输入框回车发送（支持Shift+回车换行）
        messageInput.addEventListener('keydown', function (event) {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault();
                sendMessage();
            }
        });

        // 头部点击事件 - 双击最大化/最小化（可选）
        chatHeader.addEventListener('dblclick', toggleMinimize);
    }

    // 调整输入框高度 - 优化算法
    function adjustTextareaHeight() {
        messageInput.style.height = 'auto';
        const newHeight = Math.min(messageInput.scrollHeight, 100);
        messageInput.style.height = `${newHeight}px`;
        messageInput.style.overflowY = newHeight > 40 ? 'auto' : 'hidden';
    }

    // 发送消息 - 异步优化
    async function sendMessage() {
        const message = messageInput.value.trim();
        if (!message) return;

        // 清空输入框
        messageInput.value = '';
        adjustTextareaHeight();

        // 显示用户消息
        appendMessage('user', message);

        // 设置状态为发送中
        connectionStatus.textContent = '发送中...';
        
        // 显示打字指示器
        showTypingIndicator();

        try {
            // 使用Request对象进行优化的API调用
            const response = await fetchAPI(message);
            
            // 隐藏打字指示器
            hideTypingIndicator();
            
            // 显示AI回复
            appendMessage('bot', response);
        } catch (error) {
            console.error('API调用失败:', error);
            // 隐藏打字指示器
            hideTypingIndicator();
            appendMessage('system', '抱歉，暂时无法获取回复，请稍后再试。');
        } finally {
            // 恢复状态
            connectionStatus.textContent = '就绪';
        }
    }

    // API调用 - 使用axios连接后端接口
    async function fetchAPI(message) {
        try {
            // 使用axios调用后端接口
            const response = await axios.post('/home/coze/chat', {
                message: message
            });

            return response.data;
        } catch (error) {
            console.error('API调用失败:', error);
            // 如果调用失败，返回友好的错误提示
            return '抱歉，我暂时无法连接到服务器，请稍后再试。';
        }
    }

    // 格式化消息内容 - 自定义解析器
    function formatMessageContent(content) {
        if (!content || typeof content !== 'string') {
            return '';
        }
        
        console.log('原始内容:', content);
        
        let formatted = content;
        
        // 处理列表
        formatted = formatted.replace(/^- (.+)$/gm, '<li>$1</li>');
        
        // 如果有列表项，包装成ul标签
        if (formatted.includes('<li>')) {
            formatted = formatted.replace(/(<li>.*?<\/li>)/gs, '<ul>$1</ul>');
        }
        
        // 处理粗体 **文本**
        formatted = formatted.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
        
        // 处理斜体 *文本*
        formatted = formatted.replace(/\*(.*?)\*/g, '<em>$1</em>');
        
        // 处理标题 #标题文本
        formatted = formatted.replace(/^### (.+)$/gm, '<h3>$1</h3>');
        formatted = formatted.replace(/^## (.+)$/gm, '<h2>$1</h2>');
        formatted = formatted.replace(/^# (.+)$/gm, '<h1>$1</h1>');
        
        // 处理链接 [文本](链接)
        formatted = formatted.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>');
        
        // 处理段落 - 将多个换行分组
        const paragraphs = formatted.split(/\n{2,}/);
        formatted = paragraphs.map(p => {
            p = p.trim();
            if (!p) return '';
            
            // 如果段落不包含HTML标签，用p标签包裹
            if (!p.includes('<') && !p.includes('>')) {
                return `<p>${p}</p>`;
            }
            return p;
        }).join('');
        
        // 处理单行换行
        formatted = formatted.replace(/\n/g, '<br>');
        
        console.log('格式化后内容:', formatted);
        return formatted;
    }

    // 显示消息 - 支持Markdown格式
    function appendMessage(sender, content) {
        const messageDiv = document.createElement('div');
        messageDiv.classList.add('message', sender);

        if (sender !== 'system') {
            // 非系统消息添加头像
            const avatarDiv = document.createElement('div');
            avatarDiv.classList.add('message-avatar');
            avatarDiv.textContent = sender === 'user' ? '我' : '客';
            messageDiv.appendChild(avatarDiv);
        }

        // 消息内容容器
        const contentDiv = document.createElement('div');
        contentDiv.classList.add('message-content');
        
        // 只有机器人消息才处理格式
        if (sender === 'bot') {
            contentDiv.innerHTML = formatMessageContent(content);
        } else {
            contentDiv.textContent = content;
        }
        
        messageDiv.appendChild(contentDiv);

        // 添加时间戳
        const timeSpan = document.createElement('span');
        timeSpan.classList.add('message-time');
        timeSpan.textContent = formatTime();
        messageDiv.appendChild(timeSpan);

        messagesContainer.appendChild(messageDiv);

        // 异步滚动到底部，避免UI阻塞
        setTimeout(() => {
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }, 0);
    }

    // 清空聊天记录 - 优化版本
    function clearChatHistory() {
        messagesContainer.innerHTML = '';
        // 重置打字指示器
        window._typingIndicator = null;
        // 添加欢迎消息
        appendMessage('system', '您好！我是中国梦想游智能客服，很高兴为您服务。请输入您的问题，我会尽力为您解答。');
    }

    // 最小化/最大化切换
    function toggleMinimize() {
        if (isMinimized) {
            // 最大化窗口
            chatContainer.style.height = '450px';
            messagesContainer.style.display = 'block';
            document.querySelector('.chat-input-area').style.display = 'flex';
            document.querySelector('.chat-status').style.display = 'block';
            minimizeButton.textContent = '—';
            minimizeButton.title = '最小化';
            isMinimized = false;
        } else {
            // 最小化窗口
            chatContainer.style.height = '60px';
            messagesContainer.style.display = 'none';
            document.querySelector('.chat-input-area').style.display = 'none';
            document.querySelector('.chat-status').style.display = 'none';
            minimizeButton.textContent = '□';
            minimizeButton.title = '最大化';
            isMinimized = true;
        }

        // 通知父窗口状态变化，添加try-catch避免跨域错误
        try {
            if (window.parent && typeof window.parent.onChatWindowStateChange === 'function') {
                window.parent.onChatWindowStateChange(isMinimized);
            }
        } catch (e) {
            console.log('Cross-origin communication not available:', e);
        }
    }

    // 格式化时间
    function formatTime() {
        const now = new Date();
        const hours = now.getHours().toString().padStart(2, '0');
        const minutes = now.getMinutes().toString().padStart(2, '0');
        return `${hours}:${minutes}`;
    }

    // 创建并显示打字指示器
    function showTypingIndicator() {
        // 如果已经存在打字指示器，则不重复创建
        if (window._typingIndicator) {
            return;
        }
        
        // 创建打字指示器元素
        window._typingIndicator = document.createElement('div');
        window._typingIndicator.className = 'message bot';
        
        // 添加头像
        const avatarDiv = document.createElement('div');
        avatarDiv.className = 'message-avatar';
        avatarDiv.textContent = '客';
        
        // 添加打字动画容器
        const typingDiv = document.createElement('div');
        typingDiv.className = 'typing-indicator';
        
        // 添加提示文本
        const textSpan = document.createElement('span');
        textSpan.className = 'typing-text';
        textSpan.textContent = '正在输入';
        
        // 添加动画点
        const dotsDiv = document.createElement('div');
        dotsDiv.className = 'dots';
        
        // 创建三个动画点，每个点有独立的动画延迟
        const dotElements = ['●', '●', '●'];
        dotElements.forEach((_, index) => {
            const dot = document.createElement('div');
            dot.className = 'dot';
            dot.setAttribute('data-dot-index', index);
            dotsDiv.appendChild(dot);
        });
        
        // 组装元素
        typingDiv.appendChild(textSpan);
        typingDiv.appendChild(dotsDiv);
        window._typingIndicator.appendChild(avatarDiv);
        window._typingIndicator.appendChild(typingDiv);
        
        // 添加到消息容器
        messagesContainer.appendChild(window._typingIndicator);
        
        // 滚动到底部
        setTimeout(() => {
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }, 0);
    }
    
    // 隐藏并移除打字指示器
    function hideTypingIndicator() {
        if (window._typingIndicator && window._typingIndicator.parentNode) {
            window._typingIndicator.parentNode.removeChild(window._typingIndicator);
            window._typingIndicator = null;
        }
    }

    // 初始化
    function init() {
        // 延迟初始化，提高页面加载速度
        setTimeout(() => {
            initEventListeners();
            adjustTextareaHeight();
            // 预加载样式
            connectionStatus.textContent = '就绪';
        }, 100);
    }

    // 暴露给父窗口的控制方法
    window.ChatWindow = {
        // 显示聊天窗口
        show: function () {
            chatContainer.style.display = 'flex';
            isMinimized = false;
            toggleMinimize(); // 确保完全展开
        },

        // 隐藏聊天窗口
        hide: function () {
            chatContainer.style.display = 'none';
        },

        // 最小化聊天窗口
        minimize: function () {
            if (!isMinimized) {
                toggleMinimize();
            }
        },

        // 最大化聊天窗口
        maximize: function () {
            if (isMinimized) {
                toggleMinimize();
            }
        },

        // 发送消息
        sendMessage: function (message) {
            if (message && typeof message === 'string' && message.trim()) {
                messageInput.value = message.trim();
                sendMessage();
            }
        }
    };

    // 页面加载完成后初始化
    window.addEventListener('DOMContentLoaded', init);
</script>
</body>
</html>
